package com.vivimice.lotroller.notification;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class NotificationType {

	private String name;

	public String getName() {
		return name;
	}
	
	@Override
	public String toString() {
		return name != null ? name : "<anonymous>";
	}
	
	public static NotificationType create(String name) {
		NotificationType type = new NotificationType();
		type.name = name;
		return type;
	}
	
	public static NotificationType create() {
		return create("<anonymous>");
	}

	/**
	 * Auto name each declared NotificationType.
	 * 
	 * For example:
	 * TestNetworkingEmulator declared LOAD_USER, when doNaming is called,
	 * LOAD_USER will be auto assigned a name as "TestNetworkingEmulator.LOAD_USER"
	 * 
	 * @param clazz
	 */
	public static void doAutoNaming(Class<?> clazz) {
		for (Field field : clazz.getDeclaredFields()) {
			int modifiers = field.getModifiers();
			// only process static NotificationType field
			if (NotificationType.class.isAssignableFrom(field.getType()) && 
					(modifiers & Modifier.STATIC) != 0) {
				field.setAccessible(true);
				try {
					String name = clazz.getName() + "." + field.getName();
					NotificationType type = (NotificationType) field.get(null);
					if ((modifiers & Modifier.FINAL) != 0) {
						// if the field is final, then change the name
						type.name = name;
					} else if (type == null) {
						// the field is not final, and not initialized, 
						// then create one
						type = create(name);
						field.set(null, type);
					}
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

}
